package com.alisls.shequtao.common.web.advice;

import com.alisls.shequtao.common.core.exception.CommonEnumException;
import com.alisls.shequtao.common.model.result.ExceptionEnumResult;
import com.alisls.shequtao.common.model.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 通用异常处理
 *
 * @author Ke Wang
 */
@Log4j2
public class BaseAdvice {

    /**
     * 捕获TypeMismatchException异常
     * @param typeMismatchException 异常类
     * @return ResponseEntity 返回对象
     */
    @ExceptionHandler(TypeMismatchException.class)
    public ResponseEntity<String> argumentTypeMismatchException(TypeMismatchException typeMismatchException) {
        String message = "参数类型不匹配错误！" + typeMismatchException.getMessage();
        log.error(message);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message);
    }

    /**
     * 捕获MethodArgumentNotValidException异常
     * Hibernate-Validator校验框架抛出的异常
     * @param methodArgumentNotValidException 方法参数异常类
     * @return ResponseEntity 返回对象
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> methodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException) {
        String message = "方法参数不合法错误：" + methodArgumentNotValidException.getMessage();
        log.error(message);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message);
    }

    /**
     * 捕获BizException异常
     * @param commonEnumException 业务逻辑异常
     * @return ResponseEntity 返回对象
     */
    @ExceptionHandler(CommonEnumException.class)
    public ResponseEntity<Result> commonException(CommonEnumException commonEnumException) {
        ExceptionEnumResult exceptionEnumResult = new ExceptionEnumResult(commonEnumException);
        log.error(commonEnumException.getCommonExceptionEnum().getMsg());
        return ResponseEntity.status(commonEnumException.getCommonExceptionEnum().getCode())
                .body(exceptionEnumResult);
    }

    /**
     * 捕获所有异常
     * @param e 异常
     * @return ResponseEntity 返回对象
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> exception(Exception e) {
        String message = "程序出现未知的错误：" + e.getMessage();
        log.error(message);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message);
    }
	
}
